package com.itqf.hsh.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.itqf.hsh.dto.CommonDto;
import com.itqf.hsh.mapper.userMapper;
import com.itqf.hsh.pojo.User;
import com.itqf.hsh.service.UserService;
import com.itqf.hsh.utils.StringUtils;
import com.itqf.hsh.vo.R;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

/**
 * projectName: qk_javaproject
 *
 * @author: 肖成扬
 * time: 2021/9/8 14:52
 * description:
 */
@Service
public class UserServiceImpl implements UserService {
    @Autowired
    private userMapper UserMapper;
    @Override
    public R login(User user) {
        if (user.getAccount()==null ||user.getAccount()=="") {
            return R.FAIL("账号不能为空");
        }
        QueryWrapper<User> queryWrapper=new QueryWrapper<>();
        queryWrapper.eq("account",user.getAccount());

        User dbUser =UserMapper.selectOne(queryWrapper);

        if (dbUser==null) {
            return R.FAIL("账号错误");
        }

        String password= DigestUtils.md5DigestAsHex((user.getPassword()+"sms").getBytes());
        if (!password.equals(dbUser.getPassword())) {
            return R.FAIL("密码错误!");
        }
        return R.OK("登陆成功",dbUser);
    }

    @Override
    public R changeUser(CommonDto commonDto) {
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("account",commonDto.getAccount());
        queryWrapper.eq("password", StringUtils.dealPassword(commonDto.getOld()));
        User user = UserMapper.selectOne(queryWrapper);
        if(user==null){
            return  R.FAIL("原密码错误");
        }
        user.setPassword(StringUtils.dealPassword(commonDto.getNow()));
        user.setAccount(null);
        UserMapper.updateById(user);
        return R.OK("密码修改成功");
    }

}
